﻿using System;
using System.Collections.Generic;
using BepInEx.Configuration;
using Fortune.Configuration;
using Fortune.Log;
using WebSocketSharp.Server;

namespace Fortune.Context
{
    /// <summary>
    /// 天道静态上下文
    /// </summary>
    public static class FortuneContext
    {
        private static readonly FortuneLogger logger = FortuneLogger.newInstance(typeof(FortuneContext));

        public static FortuneBepInExConfig fortuneBepInExConfig { get; set; }
        public static IFreeSql freeSql { get; set; }
        public static ConfigFile config { get; set; }
        public static WebSocketServer webSocketServer { get; set; }
        private static int initCount { get; set; } = 0;
        private static readonly Dictionary<Type, object> beanContainer;

        static FortuneContext()
        {
            beanContainer = new Dictionary<Type, object>();
        }

        // 数据库连接地址
        public static string connectionUrl
        {
            get
            {
                string dbPath = fortuneBepInExConfig.dataBasePath.Value;
                return $"Data Source={dbPath};Pooling=true;Min Pool Size=1";
            }
        }
        
        public static bool isInitialized =>
            // 初始化次数不为0则说明已经初始化过
            initCount > 0;

        public static void startFortuneApplication()
        {
            initCount++;
            logger.info($"造化玉蝶当前启动次数：{initCount}");
        }

        public static T getBean<T>()
        {
            return (T) beanContainer[typeof(T)];
        }

        public static bool registerBean(object o)
        {
            try
            {
                beanContainer.Add(o.GetType(), o);
            }
            catch (Exception e)
            {
                logger.error("注册bean失败", e);
                return false;
            }
            return true;
        }
    }
}